package com.fahai.web.service.impl;

import com.fahai.common.PageVo;
import com.fahai.web.dao.*;
import com.fahai.web.entity.LawyerCity;
import com.fahai.web.entity.LawyerGroupSkill;
import com.fahai.web.entity.LawyerInfo;
import com.fahai.web.entity.LawyerSkill;
import com.fahai.web.service.LawyerInfoService;
import com.fahai.web.vo.LawyerInfoVo;
import com.fahai.web.vo.LawyerInfotVo;
import com.fahai.web.vo.LawyerSkillVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sky on 17/5/15.
 * 查看律师信息业务层,相关说明详见项目README.md说明文档
 */
@Service
@Transactional(rollbackFor = DataAccessException.class)
public class LawyerInfoServiceImpl implements LawyerInfoService {


    @Autowired
    LawyerInfoDao lawyerInfoDao;

    @Autowired
    LawyerGroupSkillDao lawyerGroupSkillDao;

    @Autowired
    LawyerSkillDao lawyerSkillDao;

    @Autowired
    LawyerCityDao lawyerCityDao;

    @Autowired
    CityDao cityDao;

    /**
     * 根据id查询律师信息
     *
     * @param lawyerid
     * @retur
     */
    public LawyerInfo findLawyerInfo(Integer lawyerid) {
        return lawyerInfoDao.selectByPrimaryKey(lawyerid);
    }

    /**
     * 获取所有律师个人信息数组
     *
     * @return
     */
    public List<LawyerInfo> findLawyerInfoList() {
        List<LawyerInfo> lawyerInfoList = lawyerInfoDao.selectAll();
        return lawyerInfoList;
    }

    /**
     * 查看律师指定技能列表
     *
     * @param skillType
     */
    @Override
    public List<LawyerSkill> findSkillInfoList(Integer skillType) {
        LawyerSkill lawyerSkill = new LawyerSkill();
        lawyerSkill.setSkillType(skillType);
        List<LawyerSkill> lawyerSkillList = lawyerSkillDao.select(lawyerSkill);
        return lawyerSkillList;
    }

    /**
     * 查看律师列表
     * 按条件查询律师列表，看是否有参数,详见项目README.md说明文档
     *
     * @return
     */
    @Override
    public PageVo findLawyerGroupInfo(LawyerInfoVo lawyerInfoVo, PageVo pageVo) {
        Page<LawyerInfotVo> page = PageHelper.startPage(pageVo.getPageNum(), pageVo.getPageSize());
        List<LawyerInfotVo> lawyerInfoList = new ArrayList<>();
        List<Map<String, Object>> platDatas = new ArrayList<Map<String, Object>>();

        // 律师条件筛选
        List<Integer> lawerIdInfoList = lawyerInfoDao.findLawyerInfoByCondition(lawyerInfoVo);

        //获取总条数

        Long totalCount = lawyerInfoDao.findLawyerCountByCondition(lawyerInfoVo);


//            律师服务地区筛选
        List<Integer> lawyerIdCityList = lawyerCityDao.selectLawyerIdByCondition(lawyerInfoVo);
        if (!ObjectUtils.isEmpty(lawyerInfoVo.getCid())) {
            lawerIdInfoList.retainAll(lawyerIdCityList);
        }
//          律师技能筛选 擅長
        if (!ObjectUtils.isEmpty(lawyerInfoVo.getPreferFieldList())) {
            for (Integer skillId : lawyerInfoVo.getPreferFieldList()) {
                List<Integer> lawyerIdSkillList = lawyerGroupSkillDao.selectSkillByCondition(skillId);
                lawerIdInfoList.retainAll(lawyerIdSkillList);
            }
        }
//          律师技能筛选 平台

        if (!ObjectUtils.isEmpty(lawerIdInfoList)) {

            platDatas = lawyerSkillDao.selectPlatsForlawyer(lawerIdInfoList);

        }


        //在重新获取用户信息
        for (Integer lawyerid : lawerIdInfoList) {
            LawyerInfotVo lawyerInfo = lawyerInfoDao.findLawyerInfoById(lawyerid);
            lawyerInfoList.add(lawyerInfo);
        }


        pageVo.setTotal(totalCount);


        List<LawyerInfoVo> lawyerInfoVoList = new ArrayList<>();
        //遍历律师列表
        for (LawyerInfotVo li : lawyerInfoList) {
            LawyerInfoVo liv = new LawyerInfoVo();
            liv.setLawyerid(li.getLawyerid());
            liv.setLawyername(li.getLawyername());
            liv.setLawyerPhone(li.getLawyerPhone());
            liv.setLawyerStates(li.getLawyerStates());
            liv.setIsValid(li.getIsValid());
            liv.setCreateTime(li.getCreatetimeStr());
            liv.setAllUsers(li.getAllUsers());
            liv.setServicenum(li.getServicenum() == null ? 0 : li.getServicenum());
            //律师技能信息获取
            LawyerGroupSkill lawyerGroupSkill = new LawyerGroupSkill();
            lawyerGroupSkill.setLawyerid(li.getLawyerid());
            List<LawyerGroupSkill> lawyerGroupSkillList = lawyerGroupSkillDao.select(lawyerGroupSkill);

            //获取律师对应的三级地址
            List<String> cityNames = lawyerCityDao.selectCityIdByCondition(li.getLawyerid());

            StringBuffer cityName = new StringBuffer("");

            for (String str : cityNames) {

                cityName.append(str);

                cityName.append("/");

            }

            liv.setCname(("".equals(cityName.toString()) ? cityName : cityName.substring(0, cityName.length() - 1)).toString());

            for (LawyerGroupSkill lgs : lawyerGroupSkillList) {
                //获取律师技能对应文案
                LawyerSkill lawyerSkill = lawyerSkillDao.selectByPrimaryId(lgs.getSkillId());


                if (lawyerSkill.getSkillName() != null) {
                    if (lawyerSkill.getSkillType() == 11) {          //擅长领域
                        liv.setPreferField(ObjectUtils.isEmpty(liv.getPreferField()) ? (lawyerSkill.getSkillName().trim() + "|") : (liv.getPreferField() + lawyerSkill.getSkillName().trim() + "|"));
                    } else if (lawyerSkill.getSkillType() == 21) {
                        liv.setAdvExp(ObjectUtils.isEmpty(lawyerSkill.getSkillName()) ? "" : lawyerSkill.getSkillName().trim());
                    } else if (lawyerSkill.getSkillType() == 22) {
                        liv.setAdvIdn(ObjectUtils.isEmpty(lawyerSkill.getSkillName()) ? "" : lawyerSkill.getSkillName().trim());
                    } else if (lawyerSkill.getSkillType() == 23) {   //个人优势
                        liv.setAdvDeg(ObjectUtils.isEmpty(lawyerSkill.getSkillName()) ? "" : lawyerSkill.getSkillName().trim());
                    } else if (lawyerSkill.getSkillType() == 31) {   //服务平台

                        //  liv.setPlatform(ObjectUtils.isEmpty(liv.getPlatform()) ? (lawyerSkill.getSkillName().trim() + "|") : (liv.getPlatform() + lawyerSkill.getSkillName().trim() + "|"));

                    } else if (lawyerSkill.getSkillType() == 6) {    //社会荣耀
                        liv.setSocietyHoner(ObjectUtils.isEmpty(liv.getSocietyHoner()) ? (lawyerSkill.getSkillName().trim() + "|") : (liv.getSocietyHoner() + lawyerSkill.getSkillName().trim() + "|"));
                    }
                }


            }

            //循环匹配将平台加入到内容


            for (Map<String, Object> pMap : platDatas) {

                if (li.getLawyerid() == Integer.parseInt(pMap.get("lawyerid").toString())) {

                    liv.setPlatform(ObjectUtils.isEmpty(liv.getPlatform()) ? pMap.get("pro_name").toString() + "|" : liv.getPlatform() + pMap.get("pro_name").toString() + "|");

                }

            }


//            去除拼接字符最后的|
            if (liv.getPreferField() != null) {
                liv.setPreferField(liv.getPreferField().substring(0, liv.getPreferField().length() - 1));
            } else {
                liv.setPreferField("");
            }
            if (liv.getPlatform() != null) {
                liv.setPlatform(liv.getPlatform().substring(0, liv.getPlatform().length() - 1));
            } else {
                liv.setPlatform("");
            }
            if (liv.getSocietyHoner() != null) {
                liv.setSocietyHoner(liv.getSocietyHoner().substring(0, liv.getSocietyHoner().length() - 1));
            } else {
                liv.setSocietyHoner("");
            }
            lawyerInfoVoList.add(liv);
        }
        pageVo.setResult(lawyerInfoVoList);

        return pageVo;
    }

    /**
     * 查看律师管理首页的待修改页面律师信息
     * 需要携带律师的技能skillid
     *
     * @param lawyerid
     */
    @Override
    public LawyerInfoVo findLawyerInfoToUpdate(Integer lawyerid) {
        LawyerInfotVo li = lawyerInfoDao.findLawyerInfoById(lawyerid);
        LawyerInfoVo liv = new LawyerInfoVo();
        liv.setLawyerid(li.getLawyerid());
        liv.setLawyername(li.getLawyername());
        liv.setLawyerPhone(li.getLawyerPhone());
        liv.setIsValid(li.getIsValid());

        LawyerGroupSkill lawyerGroupSkill = new LawyerGroupSkill();
        lawyerGroupSkill.setLawyerid(lawyerid);

        List<LawyerGroupSkill> lawyerGroupSkillList = lawyerGroupSkillDao.select(lawyerGroupSkill);
        for (LawyerGroupSkill lgs : lawyerGroupSkillList) {
            LawyerSkill lawyerSkill = lawyerSkillDao.selectByPrimaryId(lgs.getSkillId());

            //放入到List<map>集合中
            Map<Integer, String> map = new HashMap<>();
            map.put(lgs.getSkillId(), lawyerSkill.getSkillName());
            if (lawyerSkill.getSkillType() == 6) {
                liv.honorList.add(lawyerSkill.getSkillName());
            } else if (lawyerSkill.getSkillType() == 31) {
                liv.platformListMap.add(map);
            }
        }
        return liv;
    }

    /**
     * 更新律师管理首页个人信息
     *
     * @param lawyerInfoVo
     */
    @Override
    public void updateLawyerInfo(LawyerInfoVo lawyerInfoVo) {
        //更新律师信息
        LawyerInfo lawyerInfo = new LawyerInfo();
        lawyerInfo.setLawyerid(lawyerInfoVo.getLawyerid());
        lawyerInfo.setIsValid(lawyerInfoVo.getIsValid());
        lawyerInfo.setLawyerStates(lawyerInfoVo.getLawyerStates());
        lawyerInfoDao.updateByPrimaryKeySelective(lawyerInfo);

        //更新律师技能的中间表,先删除所有的律师管理的服务平台,
        LawyerGroupSkill lawyerGroupSkill = new LawyerGroupSkill();
        lawyerGroupSkill.setLawyerid(lawyerInfoVo.getLawyerid());
        lawyerGroupSkill.setSkillType(31);      // 服务平台，只删除中间表
        lawyerGroupSkillDao.delete(lawyerGroupSkill);
        //然后重新添加律师技能表和中间表
        //添加律师的服务平台
        if (!StringUtils.isEmpty(lawyerInfoVo.getPlatform())) {
            String[] platform = lawyerInfoVo.getPlatform().split(",");
            for (int i = 0; i < platform.length; i++) {
                LawyerGroupSkill lgs = new LawyerGroupSkill();
                lgs.setLawyerid(lawyerInfoVo.getLawyerid());
                lgs.setSkillType(31);            //服务平台
                lgs.setSkillId(Integer.parseInt(platform[i]));
                lawyerGroupSkillDao.insert(lgs); //插入新数据
            }
        }
        //  修改律師社会荣誉
        if (!StringUtils.isEmpty(lawyerInfoVo.getSocietyHoner())) {
            saveLawyerSocietyHonor(lawyerInfoVo);
        }
    }

    /**
     * 批量保存律师社会荣誉
     *
     * @param lawyerInfoVo
     */
    @Override
    public void saveLawyerSocietyHonor(LawyerInfoVo lawyerInfoVo) {
        for (String honor : lawyerInfoVo.getHonorList()) {
            LawyerSkill lawyerSkill = new LawyerSkill();
            lawyerSkill.setSkillType(6);
            lawyerSkill.setSkillDesc("社会荣誉");
            lawyerSkill.setSkillName(honor);
//            更新律师技能关联表
            int key = lawyerSkillDao.insert(lawyerSkill);
            LawyerGroupSkill lawyerGroupSkill = new LawyerGroupSkill();
            lawyerGroupSkill.setLawyerid(lawyerInfoVo.getLawyerid());
            lawyerGroupSkill.setSkillType(6);
            lawyerGroupSkill.setSkillId(lawyerSkill.getSkillId());
//            更新律师技能的中间表
            lawyerGroupSkillDao.insert(lawyerGroupSkill);
        }
    }

    /**
     * 批量删除律师的社会荣誉,单独操作社会荣誉
     *
     * @param lawyerSkill
     */
    @Override
    public void deleteLawyerSocietyHonor(LawyerSkill lawyerSkill) {
//        删除中间表
        LawyerGroupSkill lgs = new LawyerGroupSkill();
        lgs.setSkillId(lawyerSkill.getSkillId());
        lawyerGroupSkillDao.delete(lgs);
//        删除技能表
        lawyerSkillDao.delete(lawyerSkill);
    }

    /**
     * 批量冻结或解冻律师账号
     *
     * @param lawyerInfoList
     */
    @Override
    public void updateFrozeLawyerAccount(List<LawyerInfo> lawyerInfoList) {
        for (LawyerInfo li : lawyerInfoList) {
            lawyerInfoDao.updateByPrimaryKeySelective(li);
        }
    }

    /**
     * 查找律师详情
     *
     * @param lawyerid
     */
    @Override
    public Map<String, Object> findLawyerDetailInfo(Integer lawyerid) {
        //律师信息
        //LawyerInfo lawyerInfo = lawyerInfoDao.selectByPrimaryKey(lawyerid);
        LawyerInfotVo lawyerInfo = lawyerInfoDao.findLawyerInfoById(lawyerid);
        //技能查询
        LawyerGroupSkill lawyerGroupSkill = new LawyerGroupSkill();
        lawyerGroupSkill.setLawyerid(lawyerid);
        List<LawyerGroupSkill> lawyerGroupSkillList = lawyerGroupSkillDao.select(lawyerGroupSkill);
//        List lawyerSkillList = new ArrayList();
        Map<Integer, Map> skillMap = new HashMap<>();
        Map<Integer, String> honorMap = new HashMap<>();
        Map<Integer, String> preferMap = new HashMap<>();
        Map<Integer, String> advantageExprMap = new HashMap<>();
        Map<Integer, String> advantageIdenMap = new HashMap<>();
        Map<Integer, String> advantageDegrMap = new HashMap<>();
        Map<Integer, String> platformMap = new HashMap<>();

        for (LawyerGroupSkill lgs : lawyerGroupSkillList) {

            if (lgs.getSkillType() == 6) {                  //社会荣誉
                honorMap.put(lgs.getSkillId(), lawyerSkillDao.selectByPrimaryId(lgs.getSkillId()).getSkillName());
            } else if (lgs.getSkillType() == 11) {          //擅长领域
                preferMap.put(lgs.getSkillId(), lawyerSkillDao.selectByPrimaryId(lgs.getSkillId()).getSkillName());
            } else if (lgs.getSkillType() == 21) {          //个人优势 经验
                advantageExprMap.put(lgs.getSkillId(), lawyerSkillDao.selectByPrimaryId(lgs.getSkillId()).getSkillName());
            } else if (lgs.getSkillType() == 22) {          //个人优势 出身
                advantageExprMap.put(lgs.getSkillId(), lawyerSkillDao.selectByPrimaryId(lgs.getSkillId()).getSkillName());
            } else if (lgs.getSkillType() == 23) {          //个人优势 学历
                advantageExprMap.put(lgs.getSkillId(), lawyerSkillDao.selectByPrimaryId(lgs.getSkillId()).getSkillName());
            } //else if (lgs.getSkillType() == 31) {           //服务平台
            //platformMap.put(lgs.getSkillId(), lawyerSkillDao.selectByPrimaryId(lgs.getSkillId()).getSkillName());
            //}
        }
        skillMap.put(6, honorMap);
        skillMap.put(11, preferMap);
        skillMap.put(21, advantageExprMap);
        //       skillMap.put(22, advantageIdenMap);
        //       skillMap.put(23, advantageDegrMap);

        //服务平台
        List<Map<String, Object>> platData = lawyerSkillDao.selectPlatsForlawyerOne(lawyerid);


        for (Map<String, Object> m : platData) {

            platformMap.put(Integer.parseInt(m.get("proid").toString()), m.get("pro_name").toString());

        }


        skillMap.put(31, platformMap);

        LawyerCity lawyerCity = new LawyerCity();
        lawyerCity.setLawyerid(lawyerid);
        ///地理位置
        List<LawyerCity> lawyerCityList = lawyerCityDao.select(lawyerCity);

        StringBuffer citySb = new StringBuffer("");

        for (LawyerCity lc : lawyerCityList) {

            citySb.append(lc.getCname() + "/");

        }


        //查询所有的skill，不是荣誉的
        List<LawyerSkill> lsAll = lawyerSkillDao.selectListNotHonor();

        /*
        Map<Integer, String> cityMap = new HashMap<>();
        for (LawyerCity lc : lawyerCityList) {

            System.out.print(cityDao.selectByPrimaryKey(lc.getCid()));

            cityMap.put(lc.getCid(), cityDao.selectByPrimaryKey(lc.getCid()).getCname());
        }

        lawyerInfoData.put("lawyerCity", cityMap);

        */
        Map<String, Object> lawyerInfoData = new HashMap<>();

        if (!"".equals(citySb.toString())) {
            lawyerInfoData.put("lawyerInfoCity", citySb.substring(0, citySb.length() - 1));
        } else {
            lawyerInfoData.put("lawyerInfoCity", "");
        }

        lawyerInfoData.put("lawyerInfo", lawyerInfo);
        lawyerInfoData.put("lawyerSkill", skillMap);
        lawyerInfoData.put("lsAll", lsAll);
        return lawyerInfoData;
    }

    /**
     * 更新律师详细信息
     *
     * @param lawyerInfo
     */
    @Override
    public void updateLawyerDetailInfo(LawyerInfo lawyerInfo) {
        lawyerInfoDao.updateByPrimaryKeySelective(lawyerInfo);
    }

    /**
     * 更新律师的地理位置
     *
     * @param lawyerCity
     */
    public void updateLawyerCity(LawyerCity lawyerCity) {

    }

    /**
     * 更新律師技能,先删除，再增加
     *
     * @param lawyerSkillVo
     */
    @Override
    public void updateLawyerSkillInfo(LawyerSkillVo lawyerSkillVo) {
        LawyerGroupSkill lawyerGroupSkill = new LawyerGroupSkill();
        lawyerGroupSkill.setLawyerid(lawyerSkillVo.getLawyerid());

        lawyerGroupSkill.setSkillType(21);
        lawyerGroupSkillDao.delete(lawyerGroupSkill);
        lawyerGroupSkill.setSkillId(lawyerSkillVo.getAdvExpId());
        lawyerGroupSkillDao.insert(lawyerGroupSkill);

        lawyerGroupSkill.setSkillType(22);
        lawyerGroupSkillDao.delete(lawyerGroupSkill);
        lawyerGroupSkill.setSkillId(lawyerSkillVo.getAdvIdnId());
        lawyerGroupSkillDao.insert(lawyerGroupSkill);

        lawyerGroupSkill.setSkillType(23);
        lawyerGroupSkillDao.delete(lawyerGroupSkill);
        lawyerGroupSkill.setSkillId(lawyerSkillVo.getAdvDegId());
        lawyerGroupSkillDao.insert(lawyerGroupSkill);
//      （这里可以存储多个条件更新）
        lawyerGroupSkill.setSkillType(31);  //服务平台
        lawyerGroupSkillDao.delete(lawyerGroupSkill);
        for (Integer skillId : lawyerSkillVo.getPlatformIdList()) {
            lawyerGroupSkill.setSkillId(skillId);
            lawyerGroupSkillDao.insert(lawyerGroupSkill);
        }
        lawyerGroupSkill.setSkillType(11);  //擅长领域
        lawyerGroupSkillDao.delete(lawyerGroupSkill);
        for (Integer skillId : lawyerSkillVo.getPreferFieldIdList()) {
            lawyerGroupSkill.setSkillId(skillId);
            lawyerGroupSkillDao.insert(lawyerGroupSkill);
        }

        lawyerGroupSkill.setSkillType(6);   //个人荣耀,要保存两张表
        lawyerGroupSkillDao.delete(lawyerGroupSkill);
        for (String honor : lawyerSkillVo.getHonorList()) {
            LawyerSkill lawyerSkill = new LawyerSkill();
            lawyerSkill.setSkillType(6);
            lawyerSkill.setSkillDesc("社会荣誉");
            lawyerSkill.setSkillName(honor);
//            更新律师技能关联表
            int keys = lawyerSkillDao.insertUseGeneratedKeys(lawyerSkill);
            lawyerGroupSkill.setSkillId(keys);
//            更新律师技能的中间表
            lawyerGroupSkillDao.insert(lawyerGroupSkill);
        }
    }

    /**
     * 修改上线下线的功能
     *
     * @param lawyerInfo
     */
    @Override
    public void updateLawyerOffline(LawyerInfo lawyerInfo) {
        lawyerInfoDao.updateByPrimaryKeySelective(lawyerInfo);
    }


    /**
     * 删除一条平台和律师的关联信息
     *
     * @param lawyerId
     */
    @Override
    public void deleteGroupSkill(Integer lawyerId, Integer skillType) {
        lawyerGroupSkillDao.deleteGroupSkill(lawyerId, skillType);
    }


    /**
     * 修改lawyer_skill信息
     *
     * @param lss
     */
    @Override
    public void batchUpdateLawyerSkill(List<LawyerSkill> lss) {
        lawyerSkillDao.batchUpdateLawyerSkill(lss);
    }


    /**
     * 修改单个律师的状态--正常-冻结-审核中
     *
     * @param lawyerInfo
     */
    @Override
    public void updateLawyerValid(LawyerInfo lawyerInfo) {
        lawyerInfoDao.updateByPrimaryKeySelective(lawyerInfo);
    }

    /**
     * 批量保存城市
     *
     * @param lcs
     */
    @Override
    public void batchSaveLawyerCity(List<LawyerCity> lcs) {

        lawyerCityDao.insertList(lcs);

    }

    /**
     * 删除地址
     *
     * @param lc
     */
    @Override
    public void deleteLawyerCity(LawyerCity lc) {
        lawyerCityDao.delete(lc);
    }


    /**
     * 批量添加skill和lawyer的关联表，lawyergroupskill
     *
     * @param lgss
     */
    @Override
    public void batchSaveLawyerGroupSkill(List<LawyerGroupSkill> lgss) {

        lawyerGroupSkillDao.insertList(lgss);

    }

    @Override
    public List<Map<String, Object>> selectProductInfoList() {
        return lawyerSkillDao.selectProductInfoList();
    }

    @Override
    public void updateLawyerPlat(List<Integer> list, Integer lawyerid) {

        lawyerSkillDao.deleteServicesGroup(lawyerid);


        if (list != null && list.size() != 0) {

            lawyerSkillDao.insertServicesGroupBatch(list, lawyerid);

        }

    }

    @Override
    public List<Map<String, Object>> selectPersonAdvantage() {
        return lawyerSkillDao.selectPersonAdvantage();
    }


    @Override
    public Map<String, Object> selectOpenIdValid(Integer lawyerid) {
        return lawyerInfoDao.selectOpenIdValid(lawyerid);
    }


    /**
     * 律师管理界面列表加载
     * @param lawyerInfoVo
     * @param pageVo
     * @return
     */
    @Override
    public PageVo findLawyerList(LawyerInfoVo lawyerInfoVo, PageVo pageVo) {
        Page<LawyerInfotVo> page = PageHelper.startPage(pageVo.getPageNum(), pageVo.getPageSize());
        pageVo.setResult(lawyerInfoDao.findLawyerInfoListByCondition(lawyerInfoVo));
        pageVo.setTotal( lawyerInfoDao.findLawyerCountByCondition(lawyerInfoVo));
        return pageVo;
    }
}

